package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 功能：
 * 作者：4204001140
 * 日期：2024/4/21 16:01
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 创建订单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        // 异常业务处理（地址为空、购物车为空）
        // 地址判断
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 购物车判断
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart =new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (list == null || list.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        User user = userMapper.getById(userId);

        // 插入购物车一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getName());
        orderMapper.insert(orders);

        // 插入购物车详情n条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insetBatch(orderDetailList);

        // 删除购物车
        shoppingCartMapper.deleteByUserId(userId);

        // 返回VO对象
        OrderSubmitVO submitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

        return submitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 订单支付成功后，通过WebSocket给商家发送一条订单提醒
        // 这里规定返回给商家的消息格式为：{type:"1为订单提醒，2为客户催单", orderId: 1, orderNumber: "1234567890"}

        log.info("发送订单提醒给商家------------------------");

        // 编辑返回的信息
        HashMap map = new HashMap<>();
        map.put("type", 1);       // 1为订单提醒，2为客户催单
        map.put("orderId", ordersDB.getId());
        map.put("orderNumber", outTradeNo);
        // 把Map集合传为JSON格式
        String json = JSON.toJSONString(map);

        // 发送消息提醒
        webSocketServer.sendToAllClient(json);

        log.info("发送订单提醒给商家完成+++++++++++++++++++++++++");
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 使用websocket给商家发送信息

        HashMap map = new HashMap();
        map.put("type", 2); //2 为客户催单
        map.put("orderId", id);
        map.put("orderNumber", ordersDB.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        // 取消订单的话，把订单的状态改为取消

        // 先判断订单是否存在
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 判断订单状态是否为待支付
        if (ordersDB.getStatus() != Orders.PENDING_PAYMENT){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 修改订单状态为取消
        ordersDB.setStatus(Orders.CANCELLED);
        // 设置取消的原因
        ordersDB.setRejectionReason(ordersCancelDTO.getCancelReason());
        // 设置取消订单的时间
        ordersDB.setCancelTime(LocalDateTime.now());

        // 更新订单信息
        orderMapper.update(ordersDB);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void completeOrder(Long id) {
        // 完成订单
        // 获取当前订单的信息
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 更改订单的状态为已完成
        ordersDB.setStatus(Orders.COMPLETED);
        // 更新订单信息
        orderMapper.update(ordersDB);
    }

    /**
     * 拒绝订单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        // 拒接订单步骤：
        // 根据id获取订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //TODO 实现微信的退款操作：退还金额给用户

        // 设置订单的状态为已取消，支付状态设置为取消
        ordersDB.setStatus(Orders.CANCELLED);
        ordersDB.setPayStatus(Orders.REFUND);
        // 设置拒单原因
        ordersDB.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        // 更新订单信息
        orderMapper.update(ordersDB);
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        // 接单

        // 根据ID获取订单
        Orders ordersDB = orderMapper.getById(ordersConfirmDTO.getId());

        // 判断订单是否存在
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 判断订单是否已取消
        if (ordersDB.getStatus() == Orders.CANCELLED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 订单状态设置为已接单
        ordersDB.setStatus(Orders.CONFIRMED);

        // 更新订单信息
        orderMapper.update(ordersDB);
    }

    /**
     * 获取订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderById(Long id) {
        Orders orders = orderMapper.getById(id);

        // 判断订单是否存在
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 获取订单详情   orderDetail集合
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将orderDetailList中的name输入字符串，以,分割
        StringBuilder sb = new StringBuilder();
        for (OrderDetail orderDetail : orderDetailList) {
            sb.append(orderDetail.getName()).append(",");
        }
        String orderDishes = sb.toString();
        orderDishes = orderDishes.substring(0, orderDishes.length() - 1);

        OrderVO orderVO = new OrderVO();
        orderVO.setOrderDishes(orderDishes);
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        // 派送订单
        // 获取订单信息
        Orders ordersDB = orderMapper.getById(id);
        // 判断订单是否存在
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 更新订单的派送时间
        ordersDB.setDeliveryTime(LocalDateTime.now());
        // 更新订单状态 派送中
        ordersDB.setStatus(Orders.DELIVERY_IN_PROGRESS);
        // 更新订单信息
        orderMapper.update(ordersDB);
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        /**
         *          * 1.使用pageHelper设置分页参数，实现分页
         *          * 2.mapper查询返回Page<T> pages
         *          * 4.返回PageResult(pages.getTotal(),pages.getRecords())
         */
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> pages = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();

        for (Orders page : pages) {

            // 获取订单详情   orderDetail集合
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(page.getId());

            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(page, orderVO);

            // 将orderDetailList中的name输入字符串，以,分割
            StringBuilder sb = new StringBuilder();
            for (OrderDetail orderDetail : orderDetailList) {
                sb.append(orderDetail.getName()).append(",");
            }
            String orderDishes = sb.toString();
            orderDishes = orderDishes.length()>0 ? orderDishes.substring(0, orderDishes.length() - 1) : "";

            orderVO.setOrderDishes(orderDishes);
            orderVOList.add(orderVO);
        }
        return new PageResult(pages.getTotal(), orderVOList);
    }

    /**
     * 查询订单和订单详情列表
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult getOrdersAndOrderDetailList(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> pages = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();

        for (Orders page : pages) {

            // 获取订单详情   orderDetail集合
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(page.getId());

            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(page, orderVO);

            // 将orderDetailList中的name输入字符串，以,分割
            StringBuilder sb = new StringBuilder();
            for (OrderDetail orderDetail : orderDetailList) {
                sb.append(orderDetail.getName()).append(",");
            }
            String orderDishes = sb.toString();
            orderDishes = orderDishes.length()>0 ? orderDishes.substring(0, orderDishes.length() - 1) : "";

            orderVO.setOrderDishes(orderDishes);
            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        }
        return new PageResult(pages.getTotal(), orderVOList);

    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 1.获取订单的信息
        Orders orders = orderMapper.getById(id);
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 2.获取订单的菜品信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 3.创建新的订单
        Orders newOrder = new Orders();
        BeanUtils.copyProperties(orders, newOrder);
        newOrder.setId(null);
        newOrder.setOrderTime(LocalDateTime.now());
        newOrder.setCheckoutTime(null);
        newOrder.setPayStatus(Orders.UN_PAID);
        newOrder.setStatus(Orders.PENDING_PAYMENT);
        newOrder.setNumber(String.valueOf(System.currentTimeMillis()));
        newOrder.setCancelTime(null);
        newOrder.setRejectionReason(null);
        newOrder.setCancelReason(null);
        newOrder.setDeliveryTime(null);
        orderMapper.insert(newOrder);
        // 4.插入订单的菜品信息
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setOrderId(newOrder.getId());
        }
        orderDetailMapper.insetBatch(orderDetailList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        /**
         * ├─ confirmed	integer	必须		待派送数量
         *
         * ├─ deliveryInProgress	integer	必须		派送中数量
         *
         * ├─ toBeConfirmed	integer	必须		待接单数量
         */

        // 1.获取订单集合
        List<Orders> ordersList = orderMapper.getAll();

        // 2.创建统计对象
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        // 3.获取 带派送 的订单数量    使用流操作实现订单状态为3的订单数量
        Long confirmed = ordersList.stream()
                .filter(orders -> orders.getStatus() == Orders.CONFIRMED)
                .count();
        orderStatisticsVO.setConfirmed(confirmed.intValue());
        // 4.获取 派送中 的订单数量
        Long deliveryInProgress = ordersList.stream()
                .filter(orders -> orders.getStatus() == Orders.DELIVERY_IN_PROGRESS)
                .count();
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress.intValue());
        // 5.获取 待接单 的订单数量
        Long toBeConfirmed = ordersList.stream()
                .filter(orders -> orders.getStatus() == Orders.TO_BE_CONFIRMED)
                .count();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed.intValue());

        // 6.设置返回统计对象的参数，返回数据
        return orderStatisticsVO;
    }


}
